package com.android.nodejs.livejs.services;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.android.nodejs.livejs.MyApplication;
import com.android.nodejs.livejs.constants.ConnectionConstants;
import com.android.nodejs.livejs.models.User;
import com.android.nodejs.livejs.utils.CommonUtil;

public class MessageService extends Service {
    
    private BufferedReader r = new BufferedReader(new InputStreamReader(MyApplication.IS_CURRENT));
    private String strServerResponse = "";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public void onCreate() {
        //1
        Log.d("ChatMessageService_onCreate", "Created");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //2
        Thread thread = new Thread(new Runnable(){
            public void run() {
                Log.d("ChatMessageService_onStartCommand", "onStartCommand");
                if(MyApplication.IS_CURRENT == null){
                    return;
                }
                try {
                    StringBuffer b = new StringBuffer();                
                    String t;
                    while ((t = r.readLine())!= null) {
                        b.append(t);
                        strServerResponse = b.toString().trim();
                        String[] des = CommonUtil.strServerResponse(strServerResponse);
                        b.delete(0, b.length());
                        if (ConnectionConstants.RES_CHANGE_PASSWORD_FAIL.equals(strServerResponse)) {
                            Intent intent = new Intent();
                            intent.setAction("CHANGE_PASSWORD");
                            intent.putExtra("msg", "0");
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_CHANGED_PASSWORD_SUCCESS.equals(strServerResponse)) {
                            Intent intent = new Intent();
                            intent.setAction("CHANGE_PASSWORD");
                            intent.putExtra("msg", "1");
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_UPDATE_PROFILE_FAIL.equals(strServerResponse)) {
                            // = 0: show toast with message update profile failures
                            Intent intent = new Intent();
                            intent.setAction("UPDATE_PROFILE");
                            intent.putExtra("msg", "0");
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_UPDATED_PROFILE_SUCCESS.equals(strServerResponse)) {
                            // = 1: show toast with message update profile success
                            Intent intent = new Intent();
                            intent.setAction("UPDATE_PROFILE");
                            intent.putExtra("msg", "1");
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_SEARCH_NO_RESULT.equals(des[0])) {
                            Intent intent = new Intent();
                            intent.setAction("SEARCH_FRIENDS");
                            Bundle bundle = new Bundle();
                            bundle.putString("msg", "0");
                            intent.putExtra("bundle", bundle);
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_SEARCH_HAVE_RESULTS.equals(des[0])) {
                            ArrayList<User> users = new ArrayList<User>();
                            List<JSONObject> jsonListFriends = CommonUtil.convertToListJSONObject(des[1]);
                            for (JSONObject json : jsonListFriends) {
                                try {
                                    User user = new User();
                                    user.setId(json.getInt("id"));
                                    user.setAvatar("http://profile.ak.fbcdn.net/hprofile-ak-ash3/c72.31.388.388/s160x160/69242_445766122158689_209300158_n.jpg");
                                    user.setFullName(json.getString("full_name"));
                                    user.setEmail(json.getString("email"));
                                    user.setBirthday(json.getString("birthday"));
                                    user.setGender(json.getInt("gender"));
                                    user.setStatus(json.getString("status"));
                                    user.setLastStatus(json.getString("last_status"));
                                    users.add(user);
                                } catch (JSONException e) {
                                    Log.d("VuVT-IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                                    e.printStackTrace();
                                }
                            }
                            Intent intent = new Intent();
                            intent.setAction("SEARCH_FRIENDS");
                            Bundle bundle = new Bundle();
                            bundle.putString("msg", "1");
                            bundle.putSerializable("users_search", users);
                            intent.putExtra("bundle", bundle);
                            getApplicationContext().sendBroadcast(intent);
                        } else if(ConnectionConstants.RES_ADD_FRIEND_FAIL.equals(des[0])) {
                            Intent intent = new Intent();
                            intent.setAction("SEARCH_FRIENDS");
                            Bundle bundle = new Bundle();
                            bundle.putString("msg", "3");
                            intent.putExtra("bundle", bundle);
                            getApplicationContext().sendBroadcast(intent);
                        } else if(ConnectionConstants.RES_ADDED_FRIEND.equals(des[0])) {
                            Intent intent = new Intent();
                            intent.setAction("SEARCH_FRIENDS");
                            Bundle bundle = new Bundle();
                            bundle.putString("msg", "4");
                            intent.putExtra("bundle", bundle);
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_EXISTED_FRIEND.equals(des[0])) {
                            Intent intent = new Intent();
                            intent.setAction("SEARCH_FRIENDS");
                            Bundle bundle = new Bundle();
                            bundle.putString("msg", "5");
                            intent.putExtra("bundle", bundle);
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_HAS_SEND_FRIEND_REQUEST.equals(des[0])) {
                            Intent intent = new Intent();
                            intent.setAction("SEARCH_FRIENDS");
                            Bundle bundle = new Bundle();
                            bundle.putString("msg", "9");
                            intent.putExtra("bundle", bundle);
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_ACCEPT_FRIEND_REQUEST_SUCCESS.equals(des[0])) {
                            Intent intent = new Intent();
                            intent.setAction("ACCEPT_FRIEND_REQUEST");
                            intent.putExtra("msg", "8");
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_ACCEPT_FRIEND_REQUEST_FAIL.equals(des[0])) {
                            Intent intent = new Intent();
                            intent.setAction("ACCEPT_FRIEND_REQUEST");
                            intent.putExtra("msg", "7");
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_FRIEND_RESPONSE.equals(des[0])) {
                            List<JSONObject> jsonListFriends = CommonUtil.convertToListJSONObject(des[1]);
                            User user = new User();
                            for (JSONObject json : jsonListFriends) {
                                try {
                                    user.setId(json.getInt("id"));
                                    user.setAvatar("http://profile.ak.fbcdn.net/hprofile-ak-ash3/c72.31.388.388/s160x160/69242_445766122158689_209300158_n.jpg");
                                    user.setFullName(json.getString("full_name"));
                                    user.setEmail(json.getString("email"));
                                    user.setBirthday(json.getString("birthday"));
                                    user.setGender(json.getInt("gender"));
                                    user.setStatus(json.getString("status"));
                                    user.setLastStatus(json.getString("last_status"));
                                } catch (JSONException e) {
                                    Log.d("VuVT-IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                                    e.printStackTrace();
                                }
                            }
                            Intent intent = new Intent();
                            intent.setAction("ADD_FRIEND");
                            intent.putExtra("user_add", user);
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_DELETE_FRIEND_FAIL.equals(des[0])) {
                            Intent intent = new Intent();
                            intent.setAction("DELETE_FRIEND");
                            intent.putExtra("msg", "0");
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_DELETED_FRIEND.equals(des[0])) {
                            // send message
                            Intent intent = new Intent();
                            intent.setAction("DELETE_FRIEND");
                            intent.putExtra("msg", "1");
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_POST_LAST_STATUS_FAIL.equals(des[0])) {
                         // send message
                            Intent intent = new Intent();
                            intent.setAction("DELETE_FRIEND");
                            intent.putExtra("msg", "3");
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_POSTED_LAST_STATUS.equals(des[0])) {
                            // send message
                            Intent intent = new Intent();
                            intent.setAction("DELETE_FRIEND");
                            intent.putExtra("msg", "4");
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_NOTIFY_FRIEND_REQUEST.equals(des[0])) {
                            List<JSONObject> arrJson = CommonUtil.convertToListJSONObject(des[1]);
                            User user = new User();
                            for (JSONObject json : arrJson) {
                                try {
                                    user.setId(json.getInt("id"));
                                    user.setAvatar("http://profile.ak.fbcdn.net/hprofile-ak-ash3/c72.31.388.388/s160x160/69242_445766122158689_209300158_n.jpg");
                                    user.setFullName(json.getString("full_name"));
                                    user.setEmail(json.getString("email"));
                                    user.setBirthday(json.getString("birthday"));
                                    user.setGender(json.getInt("gender"));
                                    user.setStatus(json.getString("status"));
                                    user.setLastStatus(json.getString("last_status"));
                                } catch (JSONException e) {
                                    Log.d("VuVT-IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                                    e.printStackTrace();
                                }
                            }
                            Intent intent = new Intent();
                            intent.setAction("NOTIFY_FRIEND_REQUEST");
                            Bundle bun = new Bundle();
                            bun.putString("msg", "6");
                            bun.putSerializable("friend_request", user);
                            intent.putExtra("bundle", bun);
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.CHAT.equals(des[0])) {
                            Intent intent = new Intent();
                            intent.setAction("MESSAGE_CHAT");
                            intent.putExtra("idGroup", des[1]);
                            intent.putExtra("idSender", des[2]);
                            intent.putExtra("nameSender", des[3]);
                            intent.putExtra("msg", des[4]);
                            getApplicationContext().sendBroadcast(intent);
                            // if ChatActivity is running
                            if(MyApplication.IS_RUNNING.get(des[1])) {
                                Intent intentItem = new Intent();
                                intentItem.setAction("MESSAGE_CHAT_ITEM");
                                intentItem.putExtra("what", "0");
                                intentItem.putExtra("idGroup", des[1]);
                                intentItem.putExtra("idSender", des[2]);
                                intentItem.putExtra("nameSender", des[3]);
                                intentItem.putExtra("msg", des[4]);
                                getApplicationContext().sendBroadcast(intentItem);
                            }
                        } else if (ConnectionConstants.RES_SEND_MSG_FAIL.equals(des[0])) {
                            Intent intent = new Intent();
                            intent.setAction("MESSAGE_CHAT_ITEM");
                            intent.putExtra("what", "1");
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_HAVE_READ_MESSAGE.equals(des[0])) {
                            Intent intent = new Intent();
                            intent.setAction("HAVE_READ_MESSAGE");
                            intent.putExtra("msg", "0");
                            getApplicationContext().sendBroadcast(intent);
                        } else if (ConnectionConstants.RES_GROUP_ID.equals(des[0])) {
                            Intent intentItem = new Intent();
                            intentItem.setAction("GET_GROUP_ID");
                            intentItem.putExtra("idGrp", des[1]);
                            intentItem.putExtra("idList", des[2]);
                            getApplicationContext().sendBroadcast(intentItem);
                        }
                    }
                } catch (IOException e) {
                    Log.d("VuVT - IOException",e.getClass().getSimpleName()+": "+e.getMessage());
                }
            }
        });
        thread.start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //3
        Log.d("ChatMessageService_onDestroy", "Destroyed");
    }
}
